from PyPDF2 import PdfFileReader, PdfFileWriter
from io import BytesIO

def splitPdf(readFile, start_page, end_page) -> BytesIO:
    target = BytesIO(readFile)
    pdfFileWriter = PdfFileWriter()
    # 获取 PdfFileReader 对象
    pdfFileReader = PdfFileReader(target)
    # 文档总页数
    num = pdfFileReader.getNumPages()
    start_page -= 0
    end_page = min(num, end_page) # 选取其中较小的部分
    for index in range(start_page, end_page):
        pageObj = pdfFileReader.getPage(index)
        pdfFileWriter.addPage(pageObj)
    # 添加完每页，再一起保存至文件中
    out = BytesIO()
    pdfFileWriter.write(out)
    return out


if __name__ == '__main__':
    with open('C:/Users/Fisher/Desktop/123.pdf', 'rb') as f:
        file = f.read()
    out = splitPdf(file, 1, 2)
    with open('C:/Users/Fisher/Desktop/456.pdf', 'wb') as f:
        f.write(out.getvalue())
